﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DatabaseComponent;

public partial class SupportControlEN : System.Web.UI.Page
{
    public Persons mobjUser
    {
        get
        {
            if (ViewState["mobjUser"] == null)
                ViewState["mobjUser"] = System.Guid.NewGuid().ToString();
            return Session[ViewState["mobjUser"].ToString()] as Persons;
        }
        set
        {
            if (ViewState["mobjUser"] == null)
                ViewState["mobjUser"] = System.Guid.NewGuid().ToString();
            Session[ViewState["mobjUser"].ToString()] = value;
        }
    }


    public List<TicketAllDetails> lstTicketAllDetailsGrid
    {
        get
        {
            if (ViewState["lstTicketAllDetailsGrid"] == null)
                ViewState["lstTicketAllDetailsGrid"] = System.Guid.NewGuid().ToString();
            return Session[ViewState["lstTicketAllDetailsGrid"].ToString()] as List<TicketAllDetails>;
        }
        set
        {
            if (ViewState["lstTicketAllDetailsGrid"] == null)
                ViewState["lstTicketAllDetailsGrid"] = System.Guid.NewGuid().ToString();
            Session[ViewState["lstTicketAllDetailsGrid"].ToString()] = value;
        }
    }


    public string sortExpression
    {
        get
        {
            if (ViewState["sortExpression"] == null)
                ViewState["sortExpression"] = System.Guid.NewGuid().ToString();
            if (Session[ViewState["sortExpression"].ToString()] == null)
                Session[ViewState["sortExpression"].ToString()] = "ModifyTime";
            return Session[ViewState["sortExpression"].ToString()] as string;
        }
        set
        {
            if (ViewState["sortExpression"] == null)
                ViewState["sortExpression"] = System.Guid.NewGuid().ToString();
            Session[ViewState["sortExpression"].ToString()] = value;
        }

    }


    public bool Ascending
    {
        get
        {
            if (ViewState["Ascending"] == null)
                ViewState["Ascending"] = System.Guid.NewGuid().ToString();
            if (Session[ViewState["Ascending"].ToString()] == null)
                Session[ViewState["Ascending"].ToString()] = false;
            return (bool)Session[ViewState["Ascending"].ToString()];
        }
        set
        {
            if (ViewState["Ascending"] == null)
                ViewState["Ascending"] = System.Guid.NewGuid().ToString();
            Session[ViewState["Ascending"].ToString()] = value;
        }
    }




    public bool ShowView
    {
        get
        {
            if (ViewState["ShowView"] == null)
                ViewState["ShowView"] = System.Guid.NewGuid().ToString();
            if (Session[ViewState["ShowView"].ToString()] == null)
                Session[ViewState["ShowView"].ToString()] = false;
            return (bool)Session[ViewState["ShowView"].ToString()];
        }
        set
        {
            if (ViewState["ShowView"] == null)
                ViewState["ShowView"] = System.Guid.NewGuid().ToString();
            Session[ViewState["ShowView"].ToString()] = value;
        }
    }



    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            checkSecurityAndCustomizePage();

            bindStatus();

            bindGrid("");
        }
    }


    /// <summary>
    /// this function will bind the status drop down box with its values
    /// </summary>
    private void bindStatus()
    {
        TicketStatusDB objTicketStatusDB = new TicketStatusDB(ConnectionStrings.LMS);
        List<TicketStatus> lstTicketStatus = objTicketStatusDB.Select("", "");
        TicketStatus ts = new TicketStatus();
        ts.TicketStatusNameAR = "الكل";
        ts.TicketStatusNameEN = "All";

        lstTicketStatus.Insert(0, ts);

        ddlStatus.DataSource = lstTicketStatus;
        ddlStatus.DataTextField = "TicketStatusNameEN";
        ddlStatus.DataValueField = "ID";
        ddlStatus.DataBind();

    }


    /// <summary>
    /// this function will check security of the current user and redirect the page if he can't access it.
    /// </summary>
    private void checkSecurityAndCustomizePage()
    {
        mobjUser = GlobalVars.getCurrentPerson();

        if ((!mobjUser.lstAllRulesIDs.Contains((long)RulesEnum.Ticket_response_page)) && (!mobjUser.lstAllRulesIDs.Contains((long)RulesEnum.Show_all_requests)))
        {
            Response.Redirect("LoginEN.aspx");
        }


        if (mobjUser.lstAllRulesIDs.Contains((long)RulesEnum.Show_all_requests))
        {
            ShowView = true;
        }
        

        
    }



    protected void grdRequests_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        grdRequests.DataSource = lstTicketAllDetailsGrid;
        grdRequests.PageIndex = e.NewPageIndex;
        grdRequests.DataBind();
    }
    protected void grdRequests_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            LinkButton lnkAssign = (LinkButton)e.Row.FindControl("lnkAssign");
            HyperLink hlView = (HyperLink)e.Row.FindControl("hlView");

            long TicketID = long.Parse (grdRequests.DataKeys[e.Row.RowIndex]["TicketID"].ToString());

            TicketDB objTicketDB = new TicketDB(ConnectionStrings.LMS);

            List<Ticket> lstTicket = objTicketDB.getTicketByID(TicketID);

            if (lstTicket.Count == 0)
                return;

            Ticket objTicket = lstTicket[0];


            TicketAllDetails objTicketAllDetails = (TicketAllDetails)e.Row.DataItem;



            if (mobjUser.Equals(objTicket.objOperator))
            {
                hlView.Visible = true;

            }
            else
            {
                hlView.Visible = false;
            }


            if (mobjUser.objMainArea.Equals(objTicket.objOwner.objMainArea) && (!mobjUser.Equals(objTicket.objOperator)) && objTicket.StatusID == 1 && objTicket.objOperator.GenID == -1)
            {
                lnkAssign.Visible = true;

            }
            else
            {
                lnkAssign.Visible = false;
            }


            if (mobjUser.lstAllRulesIDs.Contains((long)RulesEnum.Show_all_requests))
            {
                hlView.Visible = true;

                if (mobjUser.lstAllRulesIDs.Contains((long)RulesEnum.Edit_all_requests))
                {

                    if ((!mobjUser.Equals(objTicket.objOperator)) && objTicket.StatusID != 2)
                    {
                        lnkAssign.Visible = true;
                    }
                }
            }

            if (objTicketAllDetails.IsBadSituation == 1)
            {
                e.Row.ForeColor = System.Drawing.Color.Red;
                TicketSendedMailDB objTicketSendedMailDB = new TicketSendedMailDB(ConnectionStrings.LMS);
                TicketSendedMail objTicketSendedMail = new TicketSendedMail();
                objTicketSendedMail.TicketID = objTicketAllDetails.TicketID;
                List<TicketSendedMail> lstTicketSendedMail = objTicketSendedMailDB.Search(objTicketSendedMail);
                if (lstTicketSendedMail.Count == 0)
                {
                    SupportMainMailDB objSupportMainMailDB = new SupportMainMailDB(ConnectionStrings.LMS);
                    List<SupportMainMail> lstSupportMainMail = objSupportMainMailDB.Select("", "");
                    if (lstSupportMainMail.Count > 0)
                    {
                        string strMailMessage =  ("Request ID : " + objTicketSendedMail.TicketID + "\r\nArea : " + objTicketAllDetails.AreaEN + "\r\nDetails :" + objTicketAllDetails.Details + "\r\nAssigned to : " + objTicketAllDetails.AssignedToEN +  "\r\n" + " in \"iLearn\" system.").Replace("\r\n","<br />");
                        GlobalVars.SendRequestMail("Request ID " + objTicketSendedMail.TicketID + " Bad ", GlobalVars.buildMailBody(strMailMessage,false) , lstSupportMainMail[0].Email);
                        objTicketSendedMailDB.Insert(objTicketSendedMail);
                    }
                }
            }



        }
    }
    protected void grdRequests_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName == "SortCommand")
        {
            if (sortExpression == e.CommandArgument)
            {
                Ascending = !Ascending;

            }
            else
            {
                sortExpression = e.CommandArgument.ToString();
                Ascending = true;
            }

            bindGrid(txtSearch.Text);

        }

        else if (e.CommandName == "Assign")
        {

            assignTicket(e.CommandArgument.ToString());


        }
    }


    /// <summary>
    /// this function will assign the ticket to the current user
    /// </summary>
    /// <param name="p">the row index of the ticket</param>
    private void assignTicket(string p)
    {
        int rowIndex = int.Parse(p);

        for (int iRowIndex = 0; iRowIndex < grdRequests.Rows.Count; iRowIndex++)
        {
            if (grdRequests.Rows[iRowIndex].RowType == DataControlRowType.DataRow)
            {
                if (grdRequests.Rows[iRowIndex].DataItemIndex == rowIndex)
                {
                    rowIndex = grdRequests.Rows[iRowIndex].RowIndex;
                    break;
                }
            }
        }

        long TicketID = long.Parse(grdRequests.DataKeys[rowIndex]["TicketID"].ToString());


        TicketDB objTicketDB = new TicketDB(ConnectionStrings.LMS);

        List<Ticket> lstTicket = objTicketDB.getTicketByID(TicketID);

        if (lstTicket.Count == 0)
            return;

        lstTicket[0].OperatorID = mobjUser.GenID;

        objTicketDB.Update(lstTicket[0]);


        bindGrid(txtSearch.Text);



        string strTitle = "Assigned request";
        string strBody = "You assigned request ID :  " + TicketID.ToString() + " to your self in \"iLearn\" system. ";

        string MailAddress = mobjUser.Email;

        GlobalVars.SendRequestMail(strTitle, GlobalVars.buildMailBody( strBody,false), MailAddress);




        strTitle = "Assigned request";
        strBody = "Your request ID :  " + TicketID.ToString() + " assigned to operator : " + mobjUser.getFullName() + "\r\n"
            + "Phone : " + mobjUser.Phone1 + "   " + mobjUser.InnerPhone1 + " , " + mobjUser.Phone2 + "   " + mobjUser.InnerPhone2 + "\r\n"
            + "Mobile : " + mobjUser.Mobile1 + " , " + mobjUser.Mobile2 + "   " + mobjUser.InnerPhone2 + "\r\n"
            + "Email : " + mobjUser.Email;

        strBody.Replace("\r\n", "<br />");

        MailAddress = lstTicket[0].objOwner.Email;

        GlobalVars.SendRequestMail(strTitle, GlobalVars.buildMailBody(strBody, false), MailAddress);



    }




    protected void ddlStatus_SelectedIndexChanged(object sender, EventArgs e)
    {
        bindGrid(txtSearch.Text);
    }

    ///// <summary>
    ///// this function will search in open tickets and get All tickets
    ///// </summary>
    ///// <param name="txtText">the text to search for</param>
    ///// <returns>a list of tickets found</returns>
    //protected List<TicketAllDetails> search(string txtText)
    //{
    //    string asc = "DESC";
    //    if (Ascending)
    //        asc = "ASC";

    //    string strStatus = "";
    //    if (ddlStatus.SelectedValue != "-1")
    //    {
    //        strStatus = " [StatusID] = '" + ddlStatus.SelectedValue + "' AND ";

    //    }

    //    TicketAllDetailsDB objTicketAllDetailsDB = new TicketAllDetailsDB(ConnectionStrings.LMS);
    //    List<TicketAllDetails> lstRet = new List<TicketAllDetails>();

    //    if (txtText.Trim() == "")
    //    {

    //        List<TicketAllDetails> lstNew = objTicketAllDetailsDB.Select(" top 100 ", " where " + strStatus + " '1'='1'  order by [" + sortExpression + "] " + asc + " ");

    //        //lstNew = new List<Persons>(from objFol in lstNew where objFol.StatusID != 2 select objFol);
    //        return lstNew;
    //    }


    //    string[] strValues = null;
    //    if (txtText.Trim()[0] == '\"' && txtText.Trim()[txtText.Trim().Length - 1] == '\"')
    //    {
    //        try
    //        {
    //            strValues = new string[] { txtText.Trim().Substring(1, txtText.Trim().Length - 2) };
    //            if (strValues[0] == "")
    //                strValues = new string[0];
    //        }
    //        catch
    //        {
    //            strValues = new string[0];
    //        }
    //    }
    //    else
    //    {
    //        strValues = txtText.Trim().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
    //    }



    //    foreach (string strValue1 in strValues)
    //    {
    //        string strValue = strValue1;
    //        strValue = strValue.Replace("'", "''");
    //        strValue = "%" + strValue + "%";





    //        string strWhere = " where "
    //        + strStatus
    //        + " ("
    //        + " CONVERT(nvarchar,[TicketID]) LIKE '" + strValue + "'  "
    //        + " OR [Badge] LIKE '" + strValue + "' "
    //        + " OR [PersonNameEN] LIKE '" + strValue + "' "
    //        + " OR [PersonNameAR] LIKE '" + strValue + "' "
    //        + " OR [RequestTypeAR] LIKE '" + strValue + "' "
    //        + " OR [RequestTypeEN] LIKE '" + strValue + "' "
    //        + " OR [Details] LIKE '" + strValue + "' "
    //        + " OR [StatusAR] LIKE '" + strValue + "' "
    //        + " OR [StatusEN] LIKE '" + strValue + "' "
    //        + " OR [AssignedToAR] LIKE '" + strValue + "' "
    //        + " OR [AssignedToEN] LIKE '" + strValue + "' "
    //        + " OR [PriorityAR] LIKE '" + strValue + "' "
    //        + " OR [PriorityEN] LIKE '" + strValue + "' "
    //        + " OR [Note] LIKE '" + strValue + "' "
    //        + " OR [AreaAR] LIKE '" + strValue + "' "
    //        + " OR [AreaEN] LIKE '" + strValue + "' "
    //        + ")"


    //        + " order by [" + sortExpression + "] " + asc + " ";


    //        List<TicketAllDetails> lstTicketAllDetails = objTicketAllDetailsDB.Select(" top 100 ", strWhere);

    //        //lstPersons = new List<Persons>(from objFol in lstPersons where objFol.StatusID != 2 select objFol);

    //        foreach (TicketAllDetails objFol in lstTicketAllDetails)
    //        {
    //            if ((from objIn in lstRet where objIn.TicketID == objFol.TicketID select objIn).ToList().Count == 0)
    //            {
    //                lstRet.Add(objFol);
    //            }
    //        }

    //    }


    //    return lstRet;



    //}




    /// <summary>
    /// this function will search in open tickets and get All tickets
    /// </summary>
    /// <param name="txtText">the text to search for</param>
    /// <returns>a list of tickets found</returns>
    protected List<TicketAllDetails> search(string txtText)
    {
        string asc = "DESC";
        if (Ascending)
            asc = "ASC";

        string strStatus = "";
        if (ddlStatus.SelectedValue != "-1")
        {
            strStatus = " [StatusID] = '" + ddlStatus.SelectedValue + "' AND ";

        }

        TicketAllDetailsDB objTicketAllDetailsDB = new TicketAllDetailsDB(ConnectionStrings.LMS);
        List<TicketAllDetails> lstRet = new List<TicketAllDetails>();

        if (txtText.Trim() == "")
        {

            List<TicketAllDetails> lstNew = objTicketAllDetailsDB.Select(" top 100 ", " where " + strStatus + " '1'='1'  order by [" + sortExpression + "] "+ asc +" ");

            //lstNew = new List<Persons>(from objFol in lstNew where objFol.StatusID != 2 select objFol);
            return lstNew;
        }


        string[] strValues = null;
        if (txtText.Trim()[0] == '\"' && txtText.Trim()[txtText.Trim().Length - 1] == '\"')
        {
            try
            {
                strValues = new string[] { txtText.Trim().Substring(1, txtText.Trim().Length - 2) };
                if (strValues[0] == "")
                    strValues = new string[0];
            }
            catch
            {
                strValues = new string[0];
            }
        }
        else
        {
            strValues = txtText.Trim().Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
        }

        string strWhere = " where "
           + strStatus
           + " ( ";

        bool bFound = false;

        foreach (string strValue1 in strValues)
        {
            bFound = true;

            string strValue = strValue1;
            strValue = strValue.Replace("'", "''");
            strValue = "%" + strValue + "%";


            
            strWhere +=

           
            " CONVERT(nvarchar,[TicketID]) LIKE '" + strValue + "'  " 
            + " OR [Badge] LIKE '" + strValue + "' "
            + " OR [PersonNameEN] LIKE '" + strValue + "' "
            + " OR [PersonNameAR] LIKE '" + strValue + "' "
            + " OR [RequestTypeAR] LIKE '" + strValue + "' "
            + " OR [RequestTypeEN] LIKE '" + strValue + "' "
            + " OR [Details] LIKE '" + strValue + "' "
            + " OR [StatusAR] LIKE '" + strValue + "' "
            + " OR [StatusEN] LIKE '" + strValue + "' "
            + " OR [AssignedToAR] LIKE '" + strValue + "' "
            + " OR [AssignedToEN] LIKE '" + strValue + "' "
            + " OR [PriorityAR] LIKE '" + strValue + "' "
            + " OR [PriorityEN] LIKE '" + strValue + "' "
            + " OR [Note] LIKE '" + strValue + "' "
            + " OR [AreaAR] LIKE '" + strValue + "' "
            + " OR [AreaEN] LIKE '" + strValue + "' "
            + " OR ";
           

        }


        if (bFound)
        {
            strWhere = strWhere.Substring(0, strWhere.LastIndexOf("OR"));

            strWhere += " )"


            + " order by [" + sortExpression + "] " + asc + " ";

    
        }
        else
        {
            strWhere = " where " + strStatus + " '1'='1'  order by [" + sortExpression + "] " + asc + " ";
        }


        lstRet = objTicketAllDetailsDB.Select(" top 100 ", strWhere);


        return lstRet;



    }

    /// <summary>
    /// this function will bind the grid with Tickets
    /// </summary>
    /// <param name="strSearch">The text to search for</param>
    public void bindGrid(string strSearch)
    {
        lstTicketAllDetailsGrid = search(strSearch);
        grdRequests.DataSource = lstTicketAllDetailsGrid;
        grdRequests.DataBind();
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        bindGrid(txtSearch.Text);
    }
}